<template>
  <el-container style="height: 100%">
    <el-dialog
        title="新建群聊"
        v-model="dialogVisible"
        width="30%"
        >
      <span slot="footer" class="dialog-footer">
          <el-input placeholder="群聊名" v-model="newSessionName" style="margin-bottom: 20px"></el-input>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="createSession">确 定</el-button>
        </span>
    </el-dialog>
    <el-header style="height: 10%">
      <el-row>
        <el-scrollbar style="width: 100%;">
          <div class="scrollbar-flex-content">
            <p>关注</p>
            <p v-for="follow in follows" style="margin-left: 10px; margin-right: 10px">
              <el-button type="primary" @click="toOwnPage(follow)">{{ follow.username }} </el-button>
            </p>
          </div>
        </el-scrollbar>
      </el-row>
    </el-header>

    <el-container style="height: 90%;">
      <el-aside width="10%" style="margin-top: 20px">
        <el-scrollbar height="100%">
          <el-space style="width: 90%" direction="vertical">
            <el-button type="text" @click="dialogVisible = true">新建群聊</el-button>
            <p>会话</p>
            <p v-for="(session,index) in sessions" style="margin: 10px">
              <el-button type="primary" @click="changeCurMessage(index)">{{session.session.sessionname}}</el-button>
            </p>
          </el-space>
        </el-scrollbar>
      </el-aside>

      <el-main style="width: 85%; height: 100%">
        <el-scrollbar ref="scrollbarRef" style="height: 70%;" >
          <el-card style="height: 100%; overflow: auto" id="message_window">
            <p v-for="message in curmessages" class="scrollbar-message-item">
              {{ message.createtime }}<br/>
              {{ message.username }}：
              {{ message.messagebody }}
            </p>
          </el-card>
        </el-scrollbar>
        <el-card style="height: 29%; ">
          <el-input
              v-model="messagetext"
              :rows="6"
              type="textarea"
              placeholder="请输入消息"
          />
          <el-row style="align-items: end">
<!--            <el-upload-->
<!--                class="upload-demo"-->
<!--                action="https://jsonplaceholder.typicode.com/posts/"-->
<!--                :on-preview="handlePreview"-->
<!--                :on-remove="handleRemove"-->
<!--                :before-remove="beforeRemove"-->
<!--                multiple-->
<!--                :limit="1"-->
<!--                :on-exceed="handleExceed"-->
<!--                :file-list="fileList"-->
<!--                style="margin: 2px"-->
<!--            >-->
<!--              <el-button type="primary">选择图片</el-button>-->
<!--            </el-upload>-->
            <el-button @click="sendmessage" style="margin: 2px" type="primary">发送消息</el-button>
          </el-row>
        </el-card>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import {getUserInfo} from "@/utils/owninfo";
import request from "@/utils/request";
import Moment from 'moment'
import {getToken} from "@/utils/auth";
import router from "@/router";

export default {
  name: "Message",
  data() {
    return {
      messagetext:'',
      sessions:'',
      follows:'',
      curmessages:'',
      cursessionid:'',
      users:'',
      dialogVisible: false,
      newSessionName:'',
    }
  },
  created() {
    this.validateLogin();
  },
  mounted() {
    this.$mybus.on('addMessage',data=>{
      console.log(data); //控制台输出接收到的数据
      var mes = data.message;
      for(var i = 0; i < this.sessions.length; i++){
        if(this.sessions[i].session.sessionid === mes.sessionid){
          mes.createtime = Moment(mes.createtime).format('YYYY-MM-DD HH:mm:ss')
          mes.username = data.user.username
          this.sessions[i].messages.push(mes);

          if(this.cursessionid === mes.sessionid){
            console.log("滚到底")
            this.scrollToBottom()
          }
          break;
        }
      }
    })
  },
  methods: {
    validateLogin() {
      console.info("验证登录")
      // console.info(getToken())
      if(getToken() === null || getToken() === undefined || getToken() === "undefined"){
        console.info('去登陆')
        router.push("/login");
        return ;
      }
      this.load()
    },
    load(){
      request({
        url: '/session/getsessionsbyuserid',
        method: 'get',
        params:{
          userid: getUserInfo()
        }
      }).then(response => {
        let userid = getUserInfo()
        // console.log("userid: "+userid)
        console.info(response)
        this.sessions = response.data.sessions
        this.users = response.data.users

        this.curmessages = this.sessions[0].messages
        this.cursessionid = this.sessions[0].session.sessionid
        if(this.curmessages.length <= 0){
          this.curmessages.push("还没有发送消息")
        }else{
          for(var i = 0; i < this.sessions.length; i++){
            if (this.sessions[i].session.sessiontype === "private") {
              // 找出对方name
              var opId
              var opName
              if (this.sessions[i].userSessions[0].userid != userid) {
                // console.log("this.sessions[i].userSessions[0].userid: "+this.sessions[i].userSessions[0].userid + " userid: "+userid)
                opId = this.sessions[i].userSessions[0].userid
              } else {
                // console.log("this.sessions[i].userSessions[1].userid: "+this.sessions[i].userSessions[1].userid + " userid: "+userid)
                opId = this.sessions[i].userSessions[1].userid
              }

              // console.log("opId: "+opId)
              opName = this.users[opId].username
              // console.log("opName: "+opName)
              this.sessions[i].session.sessionname = opName
            }
            for(var j = 0; j < this.sessions[i].messages.length; j++){
              this.sessions[i].messages[j].createtime = Moment(this.sessions[i].messages[j].createtime).format('YYYY-MM-DD HH:mm:ss')
              this.sessions[i].messages[j].username = this.users[this.sessions[i].messages[j].userid].username;
            }
          }
          this.scrollToBottom()
        }
      }).catch(error => {
        console.info(error)
        this.$message.error("请重新登录")
      })

      request({
        url: '/follow/getfollowsbyuserid',
        method: 'get',
        params:{
          userid: getUserInfo()
        }
      }).then(response => {
        console.info(response)
        this.follows = response.data.follows
      }).catch(error => {
        console.info(error)
      })
    },
    changeCurMessage(index){
      this.curmessages = this.sessions[index].messages
      this.cursessionid = this.sessions[index].session.sessionid
      this.scrollToBottom()
    },
    sendmessage(){
      request({
        url: '/message/sendmessage',
        method: 'get',
        params:{
          userid: getUserInfo(),
          messagetype:"text",
          messagebody:this.messagetext,
          sessionid:this.cursessionid,
        }
      }).then(response => {
        console.log(response)
        this.messagetext = ''
      }).catch(error => {
        console.info(error)
        this.$message.error("发送失败")
      })
    },
    toOwnPage(follow){
      router.push({
        name:"OwnPage",//这个name就是你刚刚配置在router里边的name
        query:{
          user:JSON.stringify(follow)
        }
      })
    },
    scrollToBottom: function () {
      this.$nextTick(() => {
        // document.getElementById('message_window')
        let msg = this.$el.querySelector("#message_window") // 获取对象
        // msg.scrollTop = msg.scrollHeight // 滚动高度
        console.log(msg.scrollHeight)
        this.$refs.scrollbarRef.setScrollTop(msg.scrollHeight)
        console.log(this.$refs.scrollbarRef)
      });
    },
    createSession(){
      if(this.newSessionName!=='undefined' && this.newSessionName!==''){
        request({
          url: '/session/insertsession',
          method: 'get',
          params:{
            userid: getUserInfo(),
            sessionname: this.newSessionName,
            sessiontype: "group",
          }
        }).then(response => {
          console.log(response)
          this.$message.success("创建成功")
        }).catch(error => {
          console.info(error)
          this.$message.error("网络错误");
        })
      }
      this.dialogVisible = false
    },
  },
}
</script>

<style scoped>
.scrollbar-flex-content {
  display: flex;
}
/*.scrollbar-demo-item {*/
/*  flex-shrink: 0;*/
/*  display: flex;*/
/*  align-items: center;*/
/*  justify-content: center;*/
/*  width: 80px;*/
/*  height: 50px;*/
/*  margin: 1px;*/
/*  text-align: center;*/
/*  border-radius: 1px;*/
/*  background: var(--el-color-danger-lighter);*/
/*  color: var(--el-color-danger);*/
/*}*/

.scrollbar-message-item {
  display: flex;
  align-items: center;
  justify-content: left;
  /*height: 50px;*/
  width: 94%;
  padding: 20px;
  text-align: left;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
</style>
